const http = require('http'),
    fs = require('fs')

function lastUpdateTime(path) {
    let stats = fs.statSync(path)
    return stats.mtime
}

const source = JSON.parse(fs.readFileSync(__dirname + "\\..\\Data\\singerInfo.json"))
let path = "\\..\\Data\\singerMusicInfo\\",
    slen = source.length,
    maxCount = 4,
    countOut = 0,
    start = 1350,
    end = start + 10,
    speed = 6,
    lastTime = lastUpdateTime(__dirname + path + "S0003.json")

// 设置定时叠加
// setInterval(() => {
//     console.log('next')
//     start += speed
// end = start + 4
let miss = 1219,
    distance = 1,
    offset = 0;
// 遍历所有歌手
for (let i = miss; i < miss + distance; i++) {
    let filePath = __dirname + path + source[i].id + ".json",
        time = lastUpdateTime(filePath)
    // 判断歌曲文件是否修改过
    // if (time < lastTime) {
    if (1) {
        // 获得歌曲文件
        let fileName = source[i].id,
            resData = JSON.parse(fs.readFileSync(filePath)),
            rlen = resData.length,
            hasWrite = false,
            countInner = 0,
            passRate = 1;

        // if (rlen > 70) continue;

        // if (rlen > 200) {
        //     passRate = 0.975
        // } else if (rlen > 100) {
        //     passRate = 0.96
        // } else if (rlen > 70) {
        //     passRate = 0.95
        // }
        // if (end - i > maxCount) {
        //     maxCount = end - i
        // }
        // 遍历该歌手的所有歌曲
        for (let j = 0; j < rlen; j++) {
            // 赋初值
            resData[j].cloudUrl = ''
            resData[j].cloudPwd = ''
            resData[j].id = j
            http.get(resData[j].musicUrl, res => {
                if (res.statusCode !== 200) {
                    console.log('链接错误')
                    return
                }
                let html = ''
                res.on('data', data => {
                    html += data
                    if (html.indexOf('提取密码') !== -1) {
                        res.destroy()
                    }
                })
                res.on('close', () => {
                    let url = html.match(/(?<=")http:\/\/pan\.baidu\.com\/s.{0,30}(?="\stitle=")|(?<=em\>密码：).{4}(?=\<\/b\>)/g) || []
                    if (url.length === 2) {
                        resData[j].cloudUrl = url[0]
                        resData[j].cloudPwd = url[1]
                    } else if (url.length === 1) {
                        resData[j].cloudUrl = url[0]
                    }
                    // countInner++
                    console.log(fileName + '\t', ++countInner, "\ttarget: " + parseInt(rlen * passRate))
                    // if (countInner === rlen) {
                    //     fs.writeFileSync(__dirname + path + fileName + ".json", JSON.stringify(resData))
                    //     console.log(fileName + '：bingo!', ++countOut, 'Max: ' + speed)
                    // }

                    // if (rlen * passRate <= countInner && !hasWrite) {
                    if (rlen - countInner <= offset && !hasWrite) {
                        // 同步写入
                        fs.writeFileSync(filePath, JSON.stringify(resData))
                        // 已经写入过
                        hasWrite = true
                        console.log(fileName + ' has write not fully and miss', rlen - countInner)
                        return
                        // 异步写入
                        // fs.writeFile(__dirname + path + fileName + ".json", JSON.stringify(resData), err => {
                        //     if (err) {
                        //         console.log('写入失败')
                        //         return
                        //     }
                        //     console.log('写入成功')
                        // })
                    }

                })
                // console.log(res.data)
            })
        }
    }
}
// }, 20000)


/*
fs.readFile(__dirname + path + fileName + ".json", (err, data) => {
    if (err) {
        console.log(err)
        return
    }
    let resData = JSON.parse(data),
        len = resData.length,
        count = 0
    for (let i = 0; i < len; i++) {
        http.get(resData[i].musicUrl, res => {
            if (res.statusCode !== 200) {
                console.log('链接错误')
                return
            }
            let html = ''
            res.on('data', data => {
                html += data
                if (html.indexOf('提取密码') !== -1) {
                    res.destroy()
                }
            })
            res.on('close', () => {
                let template = `<a href="http://pan.baidu.com/s/1ntJn8u9" title="A Fine Frenzy - Almost Lover.ape下载地址" rel="nofollow" target="_blank" class="blue a_none"><h2 class="bg_gr b_b_s m_s logo mt_1 yh white" style=" height:34px; line-height:34px;">高速下载</h2></a>
                <b class="mt_1 yh d_b" style=" color:#FA4826; font-size:20px;">提取<em class="dn"></em>密码：v7il</b>
                <div class="mt_1 yahei f_16 b" style=" color:#FA4826; display:none;">提取密码：http://www.51ape.com/ape/13010.html</div>     `
                let url = html.match(/(?<=")http:\/\/pan\.baidu\.com\/s.{0,30}(?="\stitle=")|(?<=em\>密码：).{4}(?=\<\/b\>)/g)
                resData[i]['cloudUrl'] = url[0]
                resData[i]['cloudPwd'] = url[1]
                console.log(url, 'No.' + i, ++count)
                if (count === len) {
                    // console.log(resData)
                    fs.writeFileSync(__dirname + path + fileName + ".json", JSON.stringify(resData))
                    console.log(fileName + '：bingo!')
                }
            })
            // console.log(res.data)
        })
    }
})
*/

// http.get('')